package com.hospital.diagnosis.module.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket 工具类
 */
public final class WebSocketUtils
{
    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);

    // 存储 websocket session
    public static final Map<Long, WebSocketSession> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();
    public static final Map<String, Long> SESSION_USER_MAPPER = new ConcurrentHashMap<>();
    public static final Map<String, Integer> SESSION_ROLE_MAPPER = new ConcurrentHashMap<>();

    /**
     * 基于用户ID获取指定用户的session
     * @param userId 用户id
     * @return 获取指定用户的session
     */
    public static WebSocketSession getSession(Long userId) {
        return ONLINE_USER_SESSIONS.get(userId);
    }

    /**
     * 向指定session发送消息
     * @param session 用户session
     * @param message 发送内容
     */
    public static void sendMessage(WebSocketSession session, String message) {
        if (session == null) {
            return;
        }
        try {
            session.sendMessage(new TextMessage(message));
        } catch (Exception e) {
            logger.error("sendMessage Exception ",e);
        }
    }

    /**
     * 推送消息到全部客户端
     * @param message 推送内容
     */
    public static void sendMessageAll(String message) {
        ONLINE_USER_SESSIONS.forEach((userId, session) -> sendMessage(session, message));
    }

    /**
     * 推送消息给指定用户
     * @param userId 接收消息方的ID
     * @param message 文本消息
     * @return false:用户不在线 true:发送成功
     */
    public static Boolean sendMessage(Long userId, String message) {
        WebSocketSession session = getSession(userId);
        if(session != null){
            return false;
        }
        sendMessage(session, message);
        return true;
    }
}